const arr = [1, 2, 3, 4, 5, 6, 7];

// k = 3 旋转3步 输出[5,6,7,1,2,3,4]

/**
 * 1. 7旋转 [7,1,2,3,4,5,6]
 * 2. 6旋转 [6,7,1,2,4,3,5]
 * 3. 5旋转 [5,6,7,1,2,3,4]
 */

const transform = (nums, k) => {
  const n = nums.length;
  const newArr = new Array(n);
  for (let i = 0; i < n; ++i) {
    newArr[(i + k) % n] = nums[i];
  }
  for (let i = 0; i < n; ++i) {
    nums[i] = newArr[i];
  }
  return nums
};

console.log(transform(arr, 3));


function rotateArray(nums, k) {
  const n = nums.length;
  k = k % n; // 处理 k 大于数组长度的情况

  // 将整个数组反转
  reverse(nums, 0, n - 1);
  // 反转前 k 个元素
  reverse(nums, 0, k - 1);
  // 反转剩余的元素
  reverse(nums, k, n - 1);
  
  return nums;
}

function reverse(nums, start, end) {
  while (start < end) {
    const temp = nums[start];
    nums[start] = nums[end];
    nums[end] = temp;
    start++;
    end--;
  }
}

// 示例
const nums1 = [1, 2, 3, 4, 5, 6, 7];
const k1 = 3;
console.log(rotateArray(nums1, k1)); // 输出 [5, 6, 7, 1, 2, 3, 4]

const nums2 = [-1, -100, 3, 99];
const k2 = 2;
console.log(rotateArray(nums2, k2)); // 输出 [3, 99, -1, -100]
